﻿#include <QPropertyAnimation>
#include <QTimer>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDebug>
#include <QPixmap>
#include <QFontMetrics>
#include <QDesktopServices>
#include <qdatetime.h>
#include <QProcess>

#define CBTN_WIDTH  24
#define CBTN_HIGH   24
#if 0
// small
#define LTEXT_WIDTH 140
#define LTEXT_HIGH  40
#else
// big
#define LTEXT_WIDTH 128
#define LTEXT_HIGH  20
#endif
#pragma execution_character_set("utf-8")

#include "notifyWidget.h"

Notify::Notify (QWidget *parent) : QWidget(parent)
{
    const static QString defaultCSS("#notify-background {"
                               "border: 1px solid #ccc;"
                               "background:white;"
                               "border-radius: 4px;"
                               "} "
                               "#notify-title{"
                               "font-family: Microsoft YaHei UI;"
                               "font-weight: bold;"
                               "color: #333;"
                               "font-size: 18px;"
                               "}"
                               "#notify-body{"
                               "font-family: Microsoft YaHei UI;"
                               "color: #444;"
                               "font-size: 14px;"
                               "}"
                               "#notify-foot{ "
                               "font-family: Microsoft YaHei UI;"
                               "color: #888;"
                               "font-size: 10px;"
                               "}"
                               "#notify-close-btn{ "
                               "border: 0;"
                               "color: #999;"
                               "}"
                               "#notify-close-btn:hover{ "
                               "background: #ccc;"
                               "}");
    QString usingCss = "";
    mtopConfig = topConfig::getInstance();
    QFile f(mtopConfig->getNotifyCSSPath());
    if(f.open(QFile::ReadOnly))
    {
        usingCss = QString::fromUtf8(f.readAll());
    }else
    {
        usingCss = defaultCSS;
    }

    this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowSystemMenuHint| Qt::Tool | Qt::WindowStaysOnTopHint);
    this->setAttribute(Qt::WA_NoSystemBackground, true);
    this->setAttribute(Qt::WA_TranslucentBackground,true);

    mCloseReason = mouseClickAsAccept;

    backgroundLabel = new QLabel(this);
    backgroundLabel->move(0, 0);
    backgroundLabel->setObjectName("notify-background");

    QHBoxLayout *mainLayout = new QHBoxLayout(backgroundLabel);
    QVBoxLayout *contentLayout = new QVBoxLayout();

    iconLabel = new QLabel(backgroundLabel);

    iconLabel->setFixedSize(QSize(mtopConfig->getLogoWidth(), mtopConfig->getLogoHeight()));
    iconLabel->setAlignment(Qt::AlignCenter | Qt::AlignLeft);

    // Tittle
    titleLabel = new QLabel(backgroundLabel);
    titleLabel->setObjectName("notify-title");
    //titleLabel->setFixedSize(LTEXT_WIDTH, LTEXT_HIGH);
    //qDebug() << "titleLabel->setFixedSize";
    titleLabel->setFixedSize(mtopConfig->getTittleWidth(),
                             mtopConfig->getTittleHeight());
    titleLabel->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);


    // Main Message
    bodyLabel = new QLabel(backgroundLabel);
    bodyLabel->setObjectName("notify-body");
    QFont font = bodyLabel->font();
    //font.setPointSize(15);
    bodyLabel->setFont(font);
    //bodyLabel->setFixedSize(LTEXT_WIDTH, LTEXT_HIGH);
    bodyLabel->setFixedSize(mtopConfig->getBodyWidth(),
                            mtopConfig->getBodyHeight());
    bodyLabel->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);

    // Time mark
    footLabel= new QLabel(backgroundLabel);
    //footLabel->setFixedWidth(50);
    footLabel->setObjectName("notify-foot");
    footLabel->setAlignment(Qt::AlignLeft);
    footLabel->setFixedSize(mtopConfig->getFootWidth(), mtopConfig->getFootHeight());
    //footLabel->setAlignment(Qt::AlignVCenter);

    contentLayout->addWidget(titleLabel);
    //contentLayout->addSpacing(5);
    contentLayout->addWidget(bodyLabel);
    contentLayout->addWidget(footLabel);

    mainLayout->addWidget(iconLabel);
    mainLayout->addSpacing(5);
    mainLayout->addLayout(contentLayout);
    closeBtn = new QPushButton("×", backgroundLabel);
    closeBtn->setObjectName("notify-close-btn");
    closeBtn->setFixedSize(CBTN_WIDTH, CBTN_HIGH);
    connect(closeBtn, &QPushButton::clicked, this, [this]{
        mCloseReason = closeBtnAsIgnore;
        Q_EMIT disappeared();
    });
    //qDebug() << usingCss;
    this->setStyleSheet(usingCss);
}

void Notify::showGriant()
{
    /* 标题 */
    titleLabel->setText(title);
    QPixmap tempPix = QPixmap(this->icon);
    tempPix = tempPix.scaled(QSize(mtopConfig->getLogoWidth(), mtopConfig->getLogoHeight()), Qt::KeepAspectRatio);
    iconLabel->setPixmap(tempPix);
    //iconLabel->setFixedSize(mtopConfig.getLogoWidth(), mtopConfig.getLogoHeight());

    backgroundLabel->setFixedSize(this->size());
    closeBtn->move(backgroundLabel->width() - closeBtn->width(), 0);

    /* 正文 */
    // 超过长度省略号
    // QFontMetrics elidfont(bodyLabel->font());
    // QString text = elidfont.elidedText(this->body, Qt::ElideRight, bodyLabel->width() - 5);
    bodyLabel->setText(body);

    /* 辅助信息（提醒时间）*/
    footLabel->setText(timeMark.toString(" MM-dd hh:mm"));

    this->show();

    QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity", this);
    animation->setStartValue(0);
    animation->setEndValue(1);
    animation->setDuration(200);
    animation->start();
    if(displayTime > 0)
    {

    connect(animation, &QPropertyAnimation::finished, this, [animation, this](){
        animation->deleteLater();
        QTimer::singleShot(displayTime , this, [this](){
            this->hideGriant();
        });
    });
    }

}

void Notify::hideGriant()
{
    QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity", this);
    animation->setStartValue(this->windowOpacity());
    animation->setEndValue(0);
    animation->setDuration(200);
    animation->start();

    connect(animation, &QPropertyAnimation::finished, this, [animation, this](){
        this->hide();
        animation->deleteLater();
        Q_EMIT disappeared();
    });
}

bool IsFileExist(QString fullFileName)
{
    QFile file(fullFileName);
    if (file.exists())
    {
        return true;
    }
    return false;
}

void runURl(QString urlOri)
{
    QString cmd;
    QString urlNew;
    QStringList urll;
    urlNew = urlOri.trimmed();
    if((urlNew.startsWith("\"") && urlNew.endsWith("\""))||
       (urlNew.startsWith("'") && urlNew.endsWith("'")))
    {
        urlNew = urlNew.mid(1, urlNew.length() - 2);
    }
    urll = urlNew.split(" ");
    //qDebug() << urlOri;
    //qDebug() << urlNew;

    if(urll.size() == 1)
    {
        cmd = urlNew;
        //p.start(cmd);
        QDesktopServices::openUrl(QUrl(cmd,QUrl::TolerantMode));
    }else {
        cmd = urll.at(0);
        urll.removeAt(0);
        QProcess p(0);
        p.start(cmd, urll);
        //p.waitForStarted();
        //p.waitForFinished();
        //QString strTemp = QString::fromLocal8Bit(p.readAllStandardOutput());  //获得输出
        //qDebug() << strTemp;
    }
    return ;
}

void Notify::mousePressEvent(QMouseEvent *event)
{
    // 单击左键
    if(event->button() == Qt::LeftButton) {
        //qDebug() << "mCloseReason is" << mCloseReason;
        //if(mCloseReason == mouseClickAsAccept)
        if(!url.isEmpty())
        {
            runURl(url);
        }
        hideGriant();
    }
}

void Notify::setUrl(const QString &value)
{
    url = value;
}


void Notify::setBody(const QString &value)
{
    body = value;
}

void Notify::setTitle(const QString &value)
{
    title = value;
}

void Notify::setIcon(const QString &value)
{
    icon = value;
}

void Notify::setDisplayTime(int value)
{
    displayTime = value;
}

void Notify::setNotifyTime(QDateTime value)
{
    timeMark = value;
}

#if 0
QT QLable属性设置（尺寸，边框等）

font: bold; 是否粗体显示
font-family:""; 来设定字体所属家族，
font-size:20px; 来设定字体大小
font-style: nomal; 来设定字体样式
font-weight:20px; 来设定字体深浅
color：black ;字体颜色

border: 1px solid gray;边框大小，样式，颜色
border-image:""; 用来设定边框的背景图片。
border-radius:5px; 用来设定边框的弧度。可以设定圆角的按钮
border-width: 1px； 边框大小

background-color: green; 设置背景颜色
background:transparent; 设置背景为透明
color:rgb(241, 70, 62); 设置前景颜色
selection-color:rgb(241, 70, 62); 用来设定选中时候的颜色
#endif
